package com.pzhu.user.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.pzhu.base.common.utils.exceptions.Assert;
import com.pzhu.base.common.utils.result.PageData;
import com.pzhu.user.domain.entity.Menu;
import com.pzhu.user.domain.entity.converter.MenuEntityConverter;
import com.pzhu.user.domain.ro.MenuCreateRO;
import com.pzhu.user.domain.ro.MenuSearchRO;
import com.pzhu.user.domain.ro.MenuUpdateRO;
import com.pzhu.user.domain.vo.MenuSearchVO;
import com.pzhu.user.domain.vo.MenuVO;
import com.pzhu.user.domain.vo.converter.MenuVOConverter;
import com.pzhu.user.domain.vo.converter.MenuSearchVOConverter;
import com.pzhu.user.dao.MenuDAO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class MenuService {

    private final MenuDAO menuDAO;

    private final MenuEntityConverter menuEntityConverter;
    private final MenuSearchVOConverter menuSearchVOConverter;
    private final MenuVOConverter menuVOConverter;

    /**
     * 保存
     *
     * @param menuCreateRo 菜单创建请求
     * @return {@link Long }
     */
    public Long save(MenuCreateRO menuCreateRo) {
        Menu menuSaveEntity = menuEntityConverter.convert(menuCreateRo);
        menuDAO.save(menuSaveEntity);
        return menuSaveEntity.getId();
    }

    /**
     * 更新
     *
     * @param id ID
     * @param menuUpdateRo 菜单更新请求
     * @return boolean
     */
    public boolean update(Long id, MenuUpdateRO menuUpdateRo) {
        Menu menu = menuDAO.getById(id);
        Assert.assertNotNull(menu, "id 错误");
        Menu menuUpdate = menuEntityConverter.convert(id, menuUpdateRo);
        return menuDAO.updateById(menuUpdate);
    }

    /**
     * 按ID删除
     *
     * @param menuId ID
     * @return boolean
     */
    public boolean removeById(Long menuId) {
        Menu menu = menuDAO.getById(menuId);
        Assert.assertNotNull(menu, "菜单不存在！");
        menu.delete();
        return menuDAO.logicDelete(menu);
    }

    /**
     * 通过id删除
     *
     * @param ids IDs
     * @return boolean
     */
    public boolean removeByIds(List<Long> ids) {
        return menuDAO.logicDeleteByIds(ids);
    }

    /**
     * 菜单搜索
     */
    public PageData<MenuSearchVO> search(MenuSearchRO menuSearchRo) {
        Page<Menu> menuPage = menuDAO.search(menuSearchRo);
        List<MenuSearchVO> menuVOList = menuVOConverter.convert(menuPage.getRecords());
        return new PageData<>(menuVOList, menuPage.getTotalRow());
    }

    public MenuVO info(Long menuId) {
        Menu menu = menuDAO.getById(menuId);
        Assert.assertNotNull(menu, "菜单信息不存在！");
        return menuVOConverter.convert(menu);
    }
}
